#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年3月6日

@author: Administrator
'''
from account import signals, settings
from account.models import Profile
from django.contrib.auth.models import User
from django.dispatch import receiver
from common.utils import tool
from account.utils import user_cache
from account.utils.es_user import update_user_to_es
from django.db.models.signals import pre_save
from comment.handlers import update_comment_by_user
from article.handler import update_article_by_user

@receiver(signals.post_save, sender=User, dispatch_uid="account.user.save")
def user_save_handler(sender, instance, raw, created, **kwargs):
    fields = {'user':instance, 'utype':settings.UserTypeEnum.DEFAULT}
    if tool.is_mobile(instance.username):
        fields["mobile"] = instance.username
    if created:
        # 创建默认的user Profile
        Profile.objects.create(**fields)
    else:
        if not Profile.objects.filter(user_id=instance.id).exists():
            Profile.objects.create(**fields)
    #更新用户缓存
    user_cache.set(instance.id)
    
    #更新用户信息到es
    update_user_to_es(instance)
    
    #用户昵称改变
    if instance.original and instance.original["first_name"] != instance.first_name:
        update_article_by_user(instance)
        update_comment_by_user(instance)
    
@receiver(pre_save, sender=User, dispatch_uid='account.user_pre_save')
def user_pre_save_handler(sender, instance, raw, **kwargs):
    '''
    '''
    if instance.id: 
        try:
            original = User.objects.get(id=instance.id)
            instance.original = original.__dict__
        except User.DoesNotExist:
            instance.original = None
    else:
        instance.original = None
    
    
